package com.bw.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import com.bw.module_home.intent.CommentIntent
import com.bw.module_home.model.entity.CommentEntity
import com.bw.module_home.model.service.CommentService
import com.bw.module_home.state.CommentState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/29 11:29
 * @Description :
 */
class CommentViewModel: BaseModel<CommentIntent>() {

    val service: CommentService by lazy {
        CommentService()
    }
    private val _state = MutableStateFlow<CommentState>(CommentState.Init)
    val state: StateFlow<CommentState> = _state.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is CommentIntent.GetCommentInfo -> {
                        doComment(it)
                    }
                    is CommentIntent.PublishComment -> {
                        doPublishComment(it)
                    }
                }
            }
        }
    }

    /**
     * 处理发布评论
     */
    private fun doPublishComment(it: CommentIntent.PublishComment) {
//        val coroutineExceptionHandler = CoroutineExceptionHandler(handler = {_, e ->
//            if (e.message!!.contains("401")) {
//                _state.value=CommentState.PublishComment401Failed
//            }
//
//        })
        viewModelScope.launch {
            flow<ResponseEntity<CommentEntity>> {
                val data=service.publishComment(it.entity)
                emit(data)
            }.catch { e->
                _state.value=CommentState.PublishCommentFailed
            }.filter {
                it != null
            }.collect{
                if (it.code==0){
                    _state.value=CommentState.PublishCommentSuccess(it.data)
                }
                else{
                    _state.value=CommentState.PublishCommentFailed
                }
            }


        }
    }

    /**
     * 处理获取评论
     */
    private fun doComment(it: CommentIntent.GetCommentInfo) {
        viewModelScope.launch(Dispatchers.IO) {
            flow<ResponseEntity<MutableList<CommentEntity>>> {
                val data = service.getCommentById(it.datatype,it.itemid)
                emit(data)
            }.catch { e->
                _state.value=CommentState.CommentFailedState
            }.filter {
                it != null
            }.collect{
                if (it.code==0){
                    _state.value=CommentState.CommentSuccessState(it.data)
                }
                else{
                    _state.value=CommentState.CommentFailedState
                }
            }
        }
    }

}